package com.milhouz.quizzdroid.view;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.milhouz.quizzdroid.R;
import com.milhouz.quizzdroid.bean.Player;

public class PlayerResultAdapter extends ArrayAdapter<Player> {

	private Player[] items;

	public PlayerResultAdapter(Context context, int textViewResourceId, Player[] items) {
		super(context, textViewResourceId, items);
	}

	public void updateItems(Player[] items) {
		this.items = items;
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.player_result, null);
		}
		Player player = items[position];
		if (player != null) {
			TextView positionTV = (TextView) v.findViewById(R.id.positionPlayer);
			if (items.length == 1) {
				positionTV.setText("");
			} else {
				positionTV.setText(String.valueOf(position + 1));
			}
			ImageView avatarImg = (ImageView) v.findViewById(R.id.avatarPlayer);
			avatarImg.setBackgroundDrawable(AvatarUtil.getAvatarFromStats(this.getContext() //
					, player.getScore().getNbCorrectResponses() //
					, player.getScore().getNbQuestions()));

			TextView scoreTV = (TextView) v.findViewById(R.id.scorePlayer);
			scoreTV.setText(String.format(getContext().getString(R.string.game_stats_nbreponses) //
					, player.getScore().getNbCorrectResponses() //
					, player.getScore().getNbQuestions()));

			TextView timeTV = (TextView) v.findViewById(R.id.timePlayer);
			timeTV.setText(String.format(getContext().getString(R.string.game_stats_meantime) //
					, player.getScore().getMeanTimeResponseSec()));
		}
		return v;
	}
}
